package cn.lizemin.fakedata.project.axios.controller;

import cn.lizemin.fakedata.common.RespBean;
import cn.lizemin.fakedata.project.axios.entity.AxiosUser;
import cn.lizemin.fakedata.utils.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * @author 李泽民
 * @Date 2024/1/20 12:21
 * @Description
 */
@Slf4j
@RestController
@RequestMapping("/axios")
public class AxiosController {

    @GetMapping("/getAllUsers")
    public RespBean getAllUsers() throws InterruptedException {
        ArrayList<AxiosUser> users = buildFakeUsers();
        return RespBean.success(users);
    }

    @GetMapping("/getUserByName")
    public RespBean getUserByName(String name) {
        if (StringUtils.isBlank(name)) {
            return RespBean.success();
        }
        ArrayList<AxiosUser> users = buildFakeUsers();
        for (AxiosUser user : users) {
            if (name.equals(user.getName())) {
                return RespBean.success(user);
            }
        }
        return RespBean.success();
    }

    /**
     * 适用于json提交
     */
    @PostMapping("/addUser")
    public RespBean addUser(@RequestBody AxiosUser user) {
        log.info("用户{}添加成功", JSON.toJson(user));
        return RespBean.success();
    }

    /**
     * 适用于表单提交
     */
    @PostMapping("/addUserByForm")
    public RespBean addUserByForm(AxiosUser user) {
        log.info("用户{}添加成功", JSON.toJson(user));
        return RespBean.success();
    }

    private ArrayList<AxiosUser> buildFakeUsers() {
        ArrayList<AxiosUser> users = Lists.newArrayList();
        for (int i = 0; i < 5; i++) {
            AxiosUser user = new AxiosUser();
            user.setName("李泽民-" + i);
            user.setAge(20 + i);
            user.setGender(i % 2 == 0 ? "男" : "女");
            users.add(user);
        }
        return users;
    }

}
